package com.hiray.demos.service

import android.app.WallpaperManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.service.wallpaper.WallpaperService
import android.util.Log
import android.view.SurfaceHolder


/**
 * Created by hiray on 2018/5/30.
 *@author hiray
 */
class VideoWallPaperService : WallpaperService() {
    val TAG = "VideoWallPaperService"
    val PATH_KEY = "VideoPath"
    var path: String? = null


    companion object {
        fun setToWallPaper(context: Context) {
            val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                    ComponentName(context, VideoWallPaperService::class.java))
            context.startActivity(intent)
        }
    }

//    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//        if (intent != null)
//            path = intent.getStringExtra(PATH_KEY)
//
//        return super.onStartCommand(intent, flags, startId)
//    }

    override fun onCreateEngine(): Engine {
        return VideoEngine()
    }

    inner class VideoEngine : WallpaperService.Engine() {

        lateinit var mediaPlayer: MediaPlayer

        override fun onSurfaceCreated(holder: SurfaceHolder?) {
            mediaPlayer = MediaPlayer()
            Log.i(TAG, "${holder == null}")
            mediaPlayer.setSurface(holder?.surface)
            val assetManager = applicationContext.assets
            val fileDescriptor = assetManager.openFd("filthyvideo.mp4")
            mediaPlayer.setDataSource(fileDescriptor.fileDescriptor,
                    fileDescriptor.startOffset, fileDescriptor.length)
            mediaPlayer.isLooping = true
            mediaPlayer.setVolume(0f, 0f)
            mediaPlayer.prepare()
            mediaPlayer.start()

        }

        override fun onSurfaceDestroyed(holder: SurfaceHolder?) {
            super.onSurfaceDestroyed(holder)
            mediaPlayer.release()
        }
    }

}


